import Box from '@mui/joy/Box';
import * as MuiTable from '@mui/joy/Table';
import { TableData } from './interface';
import FormControl from '@mui/joy/FormControl';
import FormLabel from '@mui/joy/FormLabel';
import Sheet from '@mui/joy/Sheet';
import Select from '@mui/joy/Select';
import Typography from '@mui/joy/Typography';
import Option from '@mui/joy/Option';
import IconButton from '@mui/joy/IconButton';
import KeyboardArrowLeftIcon from '@mui/icons-material/KeyboardArrowLeft';
import KeyboardArrowRightIcon from '@mui/icons-material/KeyboardArrowRight';
import { ReactNode, useState } from 'react';
import Drawer from '@mui/joy/Drawer';
import Skeleton from '@mui/joy/Skeleton';

export interface IProps<T> {
  data: TableData<T>;
  detailPageComponent: ReactNode;
  // rowsPerPage: number;
  // currentPage: number;
  loading: boolean;
  onOpenDetail: (id: string) => void;
  onCloseDetail: () => void;
}

const Table = function <T>({
  data,
  detailPageComponent,
  loading,
  // rowsPerPage,
  // currentPage,
  onOpenDetail,
  onCloseDetail,
}: IProps<T>) {
  const [openDetail, setOpenDetail] = useState(false);

  const openDetailHandler = (id: any) => () => {
    setOpenDetail(true);
    onOpenDetail(id);
  };

  const closeDetailHandler = () => {
    setOpenDetail(false);
    onCloseDetail();
  };

  const tableData = data.data.map((item, idx) => (
    <tr
      key={`row-${idx}`}
      onClick={openDetailHandler(item.id)}
      style={{ cursor: 'pointer' }}
    >
      {Object.keys(data.headers).map((key, cell_idx) => {
        return (
          <td key={`cell-${cell_idx}`}>{item[key as keyof typeof item]}</td>
        );
      })}
    </tr>
  ));

  const tableDataLoadingSkeleton = (
    <tr key={`row-1`}>
      {Object.keys(data.headers).map((_key, cell_idx) => {
        return (
          <td key={`cell-${cell_idx}`}>
            <Skeleton variant="rectangular" width="100%" animation="wave">
              12
            </Skeleton>
          </td>
        );
      })}
    </tr>
  );

  return (
    <Sheet
      variant="outlined"
      color="neutral"
      sx={{
        width: '100%',
        borderRadius: 'sm',
        flexShrink: 1,
        overflow: 'auto',
        minHeight: 0,
      }}
    >
      <MuiTable.default
        aria-labelledby="tableTitle"
        stickyHeader
        hoverRow
        sx={{
          '--TableCell-headBackground': 'var(--joy-palette-background-level1)',
          '--Table-headerUnderlineThickness': '1px',
          '--TableRow-hoverBackground': 'var(--joy-palette-background-level1)',
          '--TableCell-paddingY': '4px',
          '--TableCell-paddingX': '8px',
        }}
      >
        <thead>
          <tr>
            {Object.keys(data.headers).map((key, idx) => (
              <th
                key={`header-${idx}`}
                style={{
                  width:
                    data.headers[key as keyof typeof data.headers]?.width ||
                    'auto',
                }}
              >
                {data.headers[key as keyof typeof data.headers]?.label}
              </th>
            ))}
          </tr>
        </thead>
        <tbody>{loading ? tableDataLoadingSkeleton : tableData}</tbody>
        <tfoot>
          <tr>
            <td colSpan={Object.keys(data.headers).length}>
              <Box
                sx={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: 2,
                  justifyContent: 'flex-end',
                }}
              >
                <FormControl orientation="horizontal" size="sm">
                  <FormLabel>Rows per page:</FormLabel>
                  <Select
                  // onChange={handleChangeRowsPerPage}
                  // value={rowsPerPage}
                  >
                    <Option value={5}>5</Option>
                    <Option value={10}>10</Option>
                    <Option value={25}>25</Option>
                  </Select>
                </FormControl>
                <Typography textAlign="center" sx={{ minWidth: 80 }}>
                  {/*{labelDisplayedRows({*/}
                  {/*  from: rows.length === 0 ? 0 : page * rowsPerPage + 1,*/}
                  {/*  to: getLabelDisplayedRowsTo(),*/}
                  {/*  count: rows.length === -1 ? -1 : rows.length,*/}
                  {/*})}*/}
                </Typography>
                <Box sx={{ display: 'flex', gap: 1 }}>
                  <IconButton
                    size="sm"
                    color="neutral"
                    variant="outlined"
                    // disabled={page === 0}
                    // onClick={() => handleChangePage(page - 1)}
                    sx={{ bgcolor: 'background.surface' }}
                  >
                    <KeyboardArrowLeftIcon />
                  </IconButton>
                  <IconButton
                    size="sm"
                    color="neutral"
                    variant="outlined"
                    // disabled={
                    //   rows.length !== -1
                    //     ? page >= Math.ceil(rows.length / rowsPerPage) - 1
                    //     : false
                    // }
                    // onClick={() => handleChangePage(page + 1)}
                    sx={{ bgcolor: 'background.surface' }}
                  >
                    <KeyboardArrowRightIcon />
                  </IconButton>
                </Box>
              </Box>
            </td>
          </tr>
        </tfoot>
      </MuiTable.default>
      <Drawer
        open={openDetail}
        onClose={closeDetailHandler}
        anchor="right"
        size="lg"
      >
        {detailPageComponent}
      </Drawer>
    </Sheet>
  );
};

export default Table;
